package cn.xiaobai;

import cn.xiaobai.utils.LoggerFactory;
import cn.xiaobai.v1.HttpHandler1;
import cn.xiaobai.v2.HttpHandler2;
import cn.xiaobai.v3.HttpHandler3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.URL;

/**
 * 手写 tomcat 通过不同版本迭代进行理解
 *
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai
 * @ClassName Tomcat
 */
public class Tomcat {

    static LoggerFactory.Logger log = LoggerFactory.getLogger(Tomcat.class);
    static int port = 8080;


    public static void main(String[] args) throws IOException {
        // v1 版本
        /*
            单个线程处理, 效率低
        * */
//        v1();

        // v2 版本
        /*
         * 采用 bio , 每个 socket 连接都创建一个线程处理
         * 比较浪费资源, 每个连接都需要创建线程, 线程得不到管理
         * */
//        v2();

        // v3 版本
        /*
            引入 servlet 规范, 自定义servlet 接口,等等的处理
        * */
        v3();

    }

    public static void v1() throws IOException {
        HttpHandler1 httpHandler1 = new HttpHandler1();
        httpHandler1.setBody(getHtml());
        httpHandler1.start();
    }

    public static void v2() throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        log.info("====== tomcat v2 监听 {} 端口", port);
        String body = getHtml();
        while (!serverSocket.isClosed()) {
            HttpHandler2 httpHandler2 = new HttpHandler2(serverSocket.accept());
            httpHandler2.setBody(body);
            new Thread(httpHandler2).start();
        }
    }

    public static void v3() throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        log.info("====== tomcat v3 监听 {} 端口", port);
        String body = getHtml();
        while (!serverSocket.isClosed()) {
            HttpHandler3 httpHandler3 = new HttpHandler3(serverSocket.accept());
            httpHandler3.setBody(body);
            new Thread(httpHandler3).start();
        }

    }


    public static String getHtml() {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        URL resource = classLoader.getResource("static/index.html");
        try (InputStream inputStream = resource.openStream()) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder context = new StringBuilder();
            String read = "";
            while ((read = bufferedReader.readLine()) != null) {
                context.append(read);
            }
            return context.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
